package com.itheima.sh.servlet;

import com.itheima.sh.tool.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/*
    goodsServlet:当用户在goods.html页面中点击浏览商品，执行该servlet，将浏览的商品存储到cookie中，然后响应给浏览器。
 */
@WebServlet("/goodsServlet")
public class GoodsServle extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取浏览的商品名
        String good = request.getParameter("good");
        //2.获取页面中的所有cookie
        Cookie cookieHistory = CookieUtils.getCookies(request, "history");
        //3.判断获取的cookie是否是null
        if (cookieHistory == null) {
            //4.如果是null  说明之前没有浏览过商品，第一次浏览,创建Cookie将商品存储到cookie中
            Cookie cookie = new Cookie("history", good);
            //5.设置cookie最大存活时间
            cookie.setMaxAge(60 * 60);
            //6.响应给浏览器
            response.addCookie(cookie);
        } else {
            // 7.如果不是null 说明之前浏览过商品
            //获取cookie中的value  ===》galaxy_chuizi
            String value = cookieHistory.getValue();
            //8.按照_下划线字符进行切割变为数组
            String[] s = value.split("_");
            //9.将数组转换为集合List
            List<String> list = Arrays.asList(s);
            //10.判断集合list中是否含有当前浏览的商品
            if (!list.contains(good)) {
                //11.不包含 {galaxy,chuizi} 不包含xiaomi 我们要将xiaomi拼接到value值
                value+="_"+good;
                cookieHistory.setValue(value);
                response.addCookie(cookieHistory);
            }
        }
    }
}